import requests
import json
from datetime import datetime, timedelta
import os

class WeatherAPI:
    def __init__(self, api_key=None):
        # 使用您提供的API密钥
        self.api_key = api_key or "c04aae632198966ddb78ba68d9cdf813"
        self.base_url = "https://api.openweathermap.org/data/2.5"
    
    def get_city_coordinates(self, city_name):
        """通过城市名称获取经纬度坐标"""
        try:
            url = f"http://api.openweathermap.org/geo/1.0/direct?q={city_name}&limit=1&appid={self.api_key}"
            response = requests.get(url, timeout=10)
            response.raise_for_status()
            data = response.json()
            
            if data and len(data) > 0:
                return data[0]['lat'], data[0]['lon']
            else:
                return None, None
        except Exception as e:
            print(f"获取城市坐标失败: {str(e)}")
            return None, None
    
    def get_current_weather(self, city_name):
        """通过城市名称获取当前天气"""
        lat, lon = self.get_city_coordinates(city_name)
        if lat is None or lon is None:
            return None
            
        try:
            url = f"{self.base_url}/weather?lat={lat}&lon={lon}&appid={self.api_key}&units=metric&lang=zh_cn"
            response = requests.get(url, timeout=10)
            response.raise_for_status()
            return response.json()
        except Exception as e:
            print(f"获取天气数据失败: {str(e)}")
            return None
    
    def get_weather_forecast(self, city_name):
        """通过城市名称获取天气预报"""
        lat, lon = self.get_city_coordinates(city_name)
        if lat is None or lon is None:
            return None
            
        try:
            url = f"{self.base_url}/forecast?lat={lat}&lon={lon}&appid={self.api_key}&units=metric&lang=zh_cn"
            response = requests.get(url, timeout=10)
            response.raise_for_status()
            return response.json()
        except Exception as e:
            print(f"获取天气预报失败: {str(e)}")
            return None
    
    def get_weather_alerts(self, city_name):
        """通过城市名称获取天气预警信息"""
        lat, lon = self.get_city_coordinates(city_name)
        if lat is None or lon is None:
            return []
            
        try:
            # 使用OneCall API获取预警信息
            url = f"https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&exclude=current,minutely,hourly,daily&appid={self.api_key}"
            response = requests.get(url, timeout=10)
            response.raise_for_status()
            data = response.json()
            
            alerts = data.get('alerts', [])
            return alerts
        except Exception as e:
            print(f"获取天气预警失败: {str(e)}")
            # 返回模拟数据作为备选
            return self.get_mock_alerts()
    
    def get_mock_alerts(self):
        """获取模拟预警数据（当API不可用时使用）"""
        # 这里返回一些模拟数据
        return [
            {
                'event': '暴雨',
                'description': '预计未来24小时内将有暴雨，降水量可能达到50毫米以上',
                'start': datetime.now().isoformat(),
                'end': (datetime.now() + timedelta(hours=24)).isoformat()
            }
        ]
    
    def get_prevention_advice(self, alert_info, crop_types=None):
        """使用AI模型生成预防建议"""
        # 如果没有作物类型信息，使用通用建议
        if not crop_types:
            crop_types = ["主要农作物"]
        
        # 构建提示词
        prompt = f"""你是一名农业专家，请根据以下天气预警信息为{crop_types}种植提供专业的预防建议：

预警类型: {alert_info.get('event', '未知')}
预警描述: {alert_info.get('description', '无详细描述')}
预警时间: 从{alert_info.get('start', '未知')}到{alert_info.get('end', '未知')}

请提供:
1. 具体的防护措施
2. 建议的操作时间
3. 需要准备的物资
4. 长期应对策略

请用中文回答，内容要详细、实用，适合农民朋友理解:"""
        
        # 这里需要调用硅基流动API来生成建议
        # 由于我们无法直接在此处调用，这个函数需要在app.py中实现
        return "需要调用硅基流动API生成建议"